import cryptoFramework from "@ohos.security.cryptoFramework"
import { DataBlob } from './types';
import * as utils from './utils'

class SeedBlob implements cryptoFramework.DataBlob {
  data: Uint8Array;

  constructor(str: string) {
    this.data = utils.StringToUint8Array(str);
  }
}

export class Random {
  randBytes(len: number, seed: string = ''): Promise<DataBlob> {
    return new Promise((resolve, reject) => {
      let rand;
      try {
        rand = cryptoFramework.createRandom();
      } catch (err) {
        reject(err);
      }

      if (seed.length > 0) {
        rand.setSeed(new SeedBlob(seed));
      }
      rand.generateRandom(len)
        .then(output => {
          resolve(output);
        })
        .catch(err => {
          reject(err);
        });
    });
  }
}